const fs = require('fs');
const path = require('path');
const fg = require('fast-glob');
const axios = require('axios');
const crypto = require('crypto');

// 你的百度翻译APP_ID和密钥
const APP_ID = '20250624002389071';
const SECRET_KEY = 'N6OC4WzlPnNPihNOu52T';


// 正则：HTML 标签间中文内容
const htmlRegex = />\s*([^<>]*[\u4e00-\u9fa5]+[^<>]*)\s*</g;
// 正则：JS 字符串中的中文
const jsRegex = /(["'`])([^"'`\n]*[\u4e00-\u9fa5]+[^"'`\n]*)\1/g;

// 计算百度翻译sign签名
function makeSign(query, salt) {
  return crypto.createHash('md5').update(APP_ID + query + salt + SECRET_KEY).digest('hex');
}

// 调用百度翻译接口
async function translateText(query, from = 'zh', to = 'en') {
  const salt = Date.now();
  const sign = makeSign(query, salt);

  try {
    const res = await axios.get('https://fanyi-api.baidu.com/api/trans/vip/translate', {
      params: {
        q: query,
        from,
        to,
        appid: APP_ID,
        salt,
        sign,
      }
    });

    if (res.data && res.data.trans_result && res.data.trans_result.length > 0) {
      // 返回翻译后的文本（拼接多个结果）
      return res.data.trans_result.map(item => item.dst).join('\n');
    } else {
      console.error('Baidu Translation API returned an exception:', res.data);
      return query; // 出错时返回原文
    }
  } catch (error) {
    console.error('❌  Translation error:', query, error.message);
    return query; // 出错时返回原文
  }
}

async function processFile(filePath) {
  const isHTML = filePath.endsWith('.html');
  const isJS = filePath.endsWith('.js');
  if (!isHTML && !isJS) return;

  let content = fs.readFileSync(filePath, 'utf-8');
  const regex = isHTML ? htmlRegex : jsRegex;
  const matches = [...content.matchAll(regex)];

  for (const match of matches) {
    const fullMatch = match[0];
    const originalText = isHTML ? match[1].trim() : match[2].trim();
    if (!originalText) continue;

    const translatedText = await translateText(originalText);
    console.log(`🔄 ${originalText} → ${translatedText}`);

    const newText = fullMatch.replace(originalText, translatedText);
    content = content.replace(fullMatch, newText);
  }

  fs.writeFileSync(filePath, content, 'utf-8');
  console.log(`✅  Overwritten original file: ${filePath}`);
}

async function run() {
  console.log('📁  Scanning HTML and JS files ..');
  const files = await fg(['**/*.html', '**/*.js'], {
    ignore: ['node_modules']
  });
  for (const file of files) {
    await processFile(file);
  }
  console.log('🎉  Translation completed! All files have been updated.');
}

run();
